package com.socool.sinofaith.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.BaseMessage;
import com.socool.sinofaith.model.CompleteTaskMessage;
import com.socool.sinofaith.model.NewVersionBean;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.QuestionAnswerReqBean;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.MyDialog;
/**
 * 更新升级
 * @author maxhsh
 *
 */
public class UpdateActivity extends BaseActivity implements
		CenterViewFactory, SpinnerViewFactory {
	ActionBarHelperBase mActionBarHelperBase;
	
	TextView current_version,new_version;
	Button btn_update;
	
	public static final String DOWNLOAD_FOLDER_NAME = "Sinofaith";
	public static final String DOWNLOAD_FILE_NAME = "Sinofaith.apk";
	public static final String KEY_NAME_DOWNLOAD_ID = "downloadId";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);
		SocoolApplication.addActivity(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);
		
		current_version=(TextView) findViewById(R.id.current_version);
		new_version=(TextView) findViewById(R.id.new_version);
		
		current_version.setText(getVersion());
		
		btn_update=(Button) findViewById(R.id.btn_update);
		btn_update.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				checkUpdate();
			}
		});
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {

		TextView tv = new TextView(this);
		tv.setText("版本更新");
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View createSpinnerView() {
		ImageView imageview = new ImageView(this);
		return imageview;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void checkUpdate(){
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.getVersion_url);
		params.put("VerNum", getVersion());
		params.put("OS", SinofaithUtil.OS);
		params.put("Platform", SinofaithUtil.did);
		params.put("did", SinofaithUtil.did);
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				Log.v("qqqq", t.toString());
				try {
					final NewVersionBean newVersionBean = HttpJsonAdapter
							.getInstance().get(t.toString(),
									NewVersionBean.class);
					if ("0".equals(newVersionBean.getResult())) {
						new_version.setText(newVersionBean.getNewVersion().get(0).getSoftVerNumber());
						MyDialog.Builder builder = new MyDialog.Builder(UpdateActivity.this);
						builder.setTitle("是否立即更新？")
								.setPositiveButton(
										"更新",
										new android.content.DialogInterface.OnClickListener() {
											@SuppressLint("NewApi")
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
//												// 显示下载对话框
												DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
												String apkUrl = ConstansJsonUrl.BASEURL+"/"+newVersionBean.getNewVersion().get(0).getDownloadPath(); 
												DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
												request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);
												long downloadId = downloadManager.enqueue(request);
												SinofaithUtil.putLong(UpdateActivity.this, KEY_NAME_DOWNLOAD_ID, downloadId);
											}
										})
								.setNegativeButton(
										"取消",
										new android.content.DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
											}
										});
						Dialog dialog = builder.create();
						dialog.show();
					}else{
						new_version.setText("您已经是最新版本");
					}
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(UpdateActivity.this, e.getMessage(),
							Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(UpdateActivity.this, strMsg,
						Toast.LENGTH_LONG).show();
			}
		});
	}
	
	/**
	 * 获取版本号
	 * @return 当前应用的版本号
	 */
	public String getVersion() {
	    try {
	        PackageManager manager = this.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
	        String version = info.versionName;
	        return version;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();

	// 接受下载完成后的intent
	@SuppressLint("NewApi")
	class DownloadCompleteReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
				long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				long downloadId = SinofaithUtil.getLong(context, KEY_NAME_DOWNLOAD_ID);
				if (downloadId == downId) {
					queryDownloadStatus(context, downloadId);
				}

			}
		}

		private void queryDownloadStatus(Context context, long downloadId) {
			DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(downloadId);
			Cursor c = downloadManager.query(query);
			if (c.moveToFirst()) {
				int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
				switch (status) {
				case DownloadManager.STATUS_PAUSED:
					Log.v("down", "STATUS_PAUSED");
				case DownloadManager.STATUS_PENDING:
					Log.v("down", "STATUS_PENDING");
				case DownloadManager.STATUS_RUNNING:
					// 正在下载，不做任何事情
					Log.v("down", "STATUS_RUNNING");
					break;
				case DownloadManager.STATUS_SUCCESSFUL:
					// 完成
					Log.v("down", "下载完成");
					String apkFilePath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath()).append(File.separator)
							.append(DOWNLOAD_FOLDER_NAME).append(File.separator).append(DOWNLOAD_FILE_NAME).toString();
					SinofaithUtil.install(context, apkFilePath);
					break;
				case DownloadManager.STATUS_FAILED:
					// 清除已下载的内容，重新下载
					Log.v("down", "STATUS_FAILED");
					downloadManager.remove(downloadId);
					break;
				}
			}
		}
	}
	
	@Override
	protected void onResume() {
		registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (receiver != null)
			unregisterReceiver(receiver);
		super.onDestroy();
	}
}
